<template>
	<div ref="chartBar" style="width: 100%; height: 100%"></div>
</template>
<script setup>
	import { onMounted, watch, defineProps,nextTick  } from 'vue'
	import * as echarts from 'echarts'
	const chartBar = ref(null)
	const Echarts = ref(null)

	const props = defineProps({
		option: {
			type: Object,
			default: {
				title: '',
				xAxis: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
				value: [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3]
			}
		}
	})
	const option = {
		title: {
			text: '南校区',
			subtext: ''
		},
		tooltip: {
			show:true,
			trigger: 'item',
			formatter: (params) => {
				if(params.componentType === "markLine"){
                    return `<p>平均使用时间： ${params.value}(小时)</p>`
				}else{
                    return `<h3 style="color:${params.color}">${params.name}</h3><p>使用时间： ${params.data}(小时)</p><p>使用频率: ${(params.data/24 * 100).toFixed(2)}%</p>`
				}
			}
		},
		legend: {
		  data: ['南区统计图']
		},
		calculable: true,
		xAxis: [
			{
				type: 'category',
				// prettier-ignore
				data: ['Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
			}
		],
		yAxis: [
			{
				type: 'value'
			}
		],
		series: [
			{
				name: '南区统计图',
				type: 'bar',
				data: [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3],
				markLine: {
					data: [{ type: 'average', name: '平均/小时' }]
				}
			}
		]
	}
	watch(props.option, (newValue) => {
		nextTick(()=>{
			option.title.text = newValue.title
		    option.xAxis[0].data = newValue.xAxis
		    option.series[0].data = newValue.value
		    Echarts.value.setOption(option)
		})
	},{deep:true,immediate:true})

	onMounted(() => {
		Echarts.value = echarts.init(chartBar.value)
		// 绘制图表
		Echarts.value.setOption(option)
		// 自适应大小
		window.onresize = () => {
			Echarts.value.resize()
		}
	})
</script>
